﻿#include "mainwidget.h"
#include "ui_mainwidget.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    // 固定窗口大小
    this->setFixedSize(this->geometry().size());

    // 去掉标题栏
    this->setWindowFlag(Qt::FramelessWindowHint);

    // 判断数据库的连接是否存在 ？ 连接 ：创建
    if(QSqlDatabase::contains("sql_default_connection")) {
        // 根据数据库默认连接名称得到连接
        db = QSqlDatabase::database("sql_default_connection");
    } else {
        // 添加数据库，获取默认连接
        db = QSqlDatabase::addDatabase("QSQLITE","sql_default_connection");
        db.setDatabaseName("mp3listDatabase.db");
    }

    // 打开数据库，打开标识（QSqlQuery类）
    if(!db.open()) {
        QMessageBox::critical(0,QObject::tr("Open Database failed !"),db.lastError().text());
    } else {
        qDebug() << "Available drivers:" << QSqlDatabase::drivers();
        // 定义查询对象，得到数据库标识
        QSqlQuery query(db);
        QString sql = "CREATE TABLE IF NOT EXISTS searchlist (id INTEGER, songname_original TEXT, singnername TEXT, album_id TEXT, hash TEXT);";

        if(!query.exec(sql)) {
            QMessageBox::critical(0,QObject::tr("create searchlist failed."),query.lastError().text());
        }

        // 歌曲历史表
        sql = "create table if not exists historylist(id integer primary key autoincrement,songname_original text,singnername text,album_id text,hash text);";
        if(!query.exec(sql)) {
            QMessageBox::critical(0,QObject::tr("create historylist failed."),query.lastError().text());
        }

        // 查询历史数据表中的插入数据
        sql = "select * from historylist;";
        if(!query.exec(sql)) {
            QMessageBox::critical(0,QObject::tr("select historylist failed."),query.lastError().text());
        }

        while (query.next()) {
            QString songname_original,singnername;
            QSqlRecord rec = query.record();
            int albumkey = rec.indexOf("songname_original");
            int hashkey = rec.indexOf("singnername");

            // 通过索引获取字段的值
            songname_original = rec.value(albumkey).toString();
            singnername = rec.value(hashkey).toString();

            QString strShow = songname_original + "----" + singnername;
            QListWidgetItem *item = new QListWidgetItem(strShow);
            ui->listWidget_Smusic_history->addItem(item);
        }
    }
    // 播放操作
    player = new QMediaPlayer;
    playerList = new QMediaPlaylist;

    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(updateDuration(qint64)));
    connect(this,SIGNAL(lyricShow(QString)),this,SLOT(lyricTextShow(QString)));

    connect(ui->listWidget_Smusic,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(playSearchMusic()));
    connect(ui->listWidget_Smusic_history,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(playHistoryMusic()));

    num = 0;
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.drawPixmap(0,0,width(),height(),QPixmap(":/new/prefix1/images/bg.png"));
}


void MainWidget::on_pushButton_quit_clicked()
{
    close();
}

void MainWidget::on_pushButton_about_clicked()
{

}

void MainWidget::on_horizontalSlider_process_valueChanged(int value)
{
    QTime time(0,value/60000,qRound((value%60000)/1000.0));
    ui->label_time->setText(time.toString("mm:ss"));
    if(isPlay == false) player->setPosition(qint64(value));
}

void MainWidget::on_horizontalSlider_process_sliderPressed()
{
    isPlay = false;
}

void MainWidget::on_horizontalSlider_process_sliderReleased()
{
    isPlay = true;
}

void MainWidget::on_pushButton_last_clicked()
{
    row--;
    if(row < 0) row = ui->listWidget_Smusic_history->count();

    QSqlQuery query(db);
    QString sql = QString("select * from historylist where id=%1;").arg(row + 1);

    if(!query.exec(sql)) {
        QMessageBox::critical(0,QObject::tr("select failed !"),query.lastError().text());
    }

    QString album_id,hash;
    while(query.next()) {
        QSqlRecord recd = query.record();
        int albumkey = recd.indexOf("album_id");
        int hashkey = recd.indexOf("hash");
        album_id = query.value(albumkey).toString();
        hash = query.value(hashkey).toString();
    }
    downloadAndPlay(album_id,hash);
}

void MainWidget::on_pushButton_Play_clicked()
{
    if(isPlay == false) {
        ui->pushButton_Play->setIcon(QIcon(":/new/prefix1/images/play.png"));
        isPlay = true;
    }
    else {
        isPlay = !isPlay;
        ui->pushButton_Play->setIcon(QIcon(":/new/prefix1/images/play&pause.png"));
    }
    if(player->state() == QMediaPlayer::PlayingState) player->pause();
    else if(player->state() == QMediaPlayer::PausedState) player->play();

}

void MainWidget::on_pushButton_next_clicked()
{
    row++;
    if(row > ui->listWidget_Smusic_history->count()) row = 0;

    QSqlQuery query(db);
    QString sql = QString("select * from historylist where id=%1;").arg(row + 1);

    if(!query.exec(sql)) {
        QMessageBox::critical(0,QObject::tr("select failed !"),query.lastError().text());
    }

    QString album_id,hash;
    while(query.next()) {
        QSqlRecord recd = query.record();
        int albumkey = recd.indexOf("album_id");
        int hashkey = recd.indexOf("hash");
        album_id = query.value(albumkey).toString();
        hash = query.value(hashkey).toString();
    }
    downloadAndPlay(album_id,hash);
}

void MainWidget::on_pushButton_recycle_clicked()
{
    // TODO:
}

void MainWidget::on_horizontalSlider_valume_valueChanged(int value)
{
    player->setVolume(value);
    ui->label_volume->setText(QString::number(value));
}

void MainWidget::on_pushButton_search_clicked()
{
    // 清空搜索列表
    ui->listWidget_Smusic->clear();

    // 清理数据库中已经存储的hash数据
    QSqlQuery query(db);
    QString sql = "delete from searchlist;";

    if(!query.exec(sql)) {
        QMessageBox::critical(0,QObject::tr("Delete failed."),query.lastError().text());
    }

    // 根据用户输入的音乐名称，发起请求(调用酷狗api)
    QString url = kugouSearchApi + QString("format=json&keyword=%1&page=1&pagesize=20&showtype=1").arg(ui->lineEdit_Mname->text());
    httpAccess(url);

    QByteArray jsonData;
    QEventLoop loop;

    auto c = connect(this,finish,[&](const QByteArray &data)
    {
        jsonData = data;
        loop.exit(1);
    });

    loop.exec();
    disconnect(c);

    // 解析网页回复数据，将搜索到的hash和album_id与列表的索引值存入数据库
    hashJsonAnalysis(jsonData);
}

void MainWidget::updateDuration(qint64 value)
{
    ui->horizontalSlider_process->setRange(0,player->duration());
    ui->horizontalSlider_process->setValue(value);
}

void MainWidget::netReply(QNetworkReply *reply)
{
    // 获取响应信息，状态码为200为正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << status_code;

    reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if(reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        emit finish(data);
    } else {
        qDebug() << reply->errorString();
    }
    reply->deleteLater();
}

void MainWidget::lyricTextShow(QString lyric)
{
    ui->textBrowser_lyric->setFont(QFont("宋体",10,QFont::Bold));
    ui->textBrowser_lyric->setTextColor(Qt::black);
    ui->textBrowser_lyric->setText(lyric);
}

void MainWidget::playSearchMusic()
{
    // 获取歌曲的索引
    int row = ui->listWidget_Smusic->currentRow();
    qDebug() << "row---->" << row + 1;

    QSqlQuery query(db);
    QString sql = QString("select * from searchlist where id=%1;").arg(row + 1);
    if(!query.exec(sql)) {
        QMessageBox::critical(0,QObject::tr("selecct Failed !"),query.lastError().text());
    }

    QString songname_original,singername,album_id,hash;
    if (query.size() == 0) {
           qDebug() << "No records found.";
    }
    while(query.next()) {
        QSqlRecord recd = query.record();
        int songkey = recd.indexOf("songname_original");
        int singerkey = recd.indexOf("singername");
        int albumkey = recd.indexOf("album_id");
        int hashkey = recd.indexOf("hash");

        songname_original = recd.value(albumkey).toString();
        singername = recd.value(hashkey).toString();

        album_id = query.value(albumkey).toString();
        hash = query.value(hashkey).toString();

        sql = QString("select hash from historylist where hash='%1';").arg(hash);
        if(!query.exec(sql)) {
            QMessageBox::critical(0,QObject::tr("selecct Failed !"),query.lastError().text());
        }
        if(query.next() == NULL) {
            sql = QString("insert into historylist values(NULL,'%1','%2','%3','%4');").arg(songname_original).arg(singername).arg(album_id).arg(hash);
            if(!query.exec(sql)) {
                QMessageBox::critical(0,QObject::tr("insert Failed !"),query.lastError().text());
            }
            QString show = songname_original + "----" + singername;
            QListWidgetItem *item = new QListWidgetItem(show);
            ui->listWidget_Smusic_history->addItem(item);
        }
    }
    downloadAndPlay(album_id,hash);
}

void MainWidget::playHistoryMusic()
{
    row = ui->listWidget_Smusic_history->currentRow();
    QSqlQuery query(db);
    QString sql = QString("select * from historylist where id=%1;").arg(row + 1);
    if(!query.exec(sql)) {
        QMessageBox::critical(0,QObject::tr("selecct Failed !"),query.lastError().text());
    }
    QString album_id,hash;
    while(query.next()) {
        QSqlRecord recd = query.record();

        int albumkey = recd.indexOf("album_id");
        int hashkey = recd.indexOf("hash");

        album_id = query.value(albumkey).toString();
        hash = query.value(hashkey).toString();
    }
    downloadAndPlay(album_id,hash);

}

void MainWidget::downloadAndPlay(QString album_id, QString hash)
{
    QString url = kugouDownloadApi + QString("r=play/getdata"
                                             "&hash=%1&album_id=%2"
                                             "&dfid=1spkkh3QKS9P0iJupz0oty5G"
                                             "&mid=de94e92794f31e9cd6ff4cb309d2baa2"
                                             "&platid=4"
                                             ).arg(hash).arg(album_id);

    httpAccess(url);

    QByteArray jsonData;
    QEventLoop loop;
    auto d = connect(this,finish,[&](const QByteArray &data){
       jsonData = data;
       loop.exit(1);
    });
    loop.exec();
    disconnect(d);

    // 解析音乐
    QString music = musicJsonAnalysis(jsonData);
    player->setMedia(QUrl(music));

    player->setVolume(100);

    ui->horizontalSlider_valume->setValue(100);

    player->play();
}

void MainWidget::httpAccess(QString url)
{
    // 实例化网络请求操作事项
    request = new QNetworkRequest;
    // 将url地址存入request
    request->setUrl(url);

    // 网络管理
    manager = new QNetworkAccessManager;
    // 通过get方法，上传请求
    manager->get(*request);

    // 网页回复消息，触发finished信号，获取信息
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(netReply(QNetworkReply*)));
}

void MainWidget::hashJsonAnalysis(QByteArray jsonData)
{
    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    if(document.isObject()) {
        QJsonObject data = document.object();

        if(data.contains("data")) {
            QJsonObject objectInfo = data.value("data").toObject();

            if(objectInfo.contains("info")) {
                QJsonArray objectHash = objectInfo.value("info").toArray();

                for(int i = 0;i < objectHash.count();++i) {
                    QString songname_original,singername,album_id,hash;
                    QJsonObject album = objectHash.at(i).toObject();

                    if(album.contains("album_id")) {
                        album_id = album.value("album_id").toString();
                    }
                    if(album.contains("singername")) {
                        singername = album.value("singername").toString();
                    }
                    if(album.contains("songname_original")) {
                        songname_original = album.value("songname_original").toString();
                    }
                    if(album.contains("hash")) {
                        hash = album.value("hash").toString();
                    }

                    QSqlQuery query(db);
                    QString sql = QString("insert into searchlist values(%1,'%2','%3','%4','%5')").arg(QString::number(i)).arg(songname_original).arg(singername).arg(album_id).arg(hash);

                    if(!query.exec(sql)) {
                        QMessageBox::critical(0,QObject::tr("insert failed !"),query.lastError().text());
                    }

                    // 将解析的音乐存入控件并显示
                    QString show = songname_original + "----" + singername;
                    QListWidgetItem *item = new QListWidgetItem(show);
                    ui->listWidget_Smusic->addItem(item);

                }
            }
        }
    }
    if(document.isArray()) {
        qDebug() << "Array";
    }
}

QString MainWidget::musicJsonAnalysis(QByteArray jsonData)
{
    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    if(document.isObject()) {
        QJsonObject data = document.object();
        if(data.contains("data")) {
            QJsonObject objectPlayUrl = data.value("data").toObject();

            if(objectPlayUrl.contains("lyrics")) {
                emit lyricshow(objectPlayUrl.value("lyrics").toString());
            }
            if(objectPlayUrl.contains("play_url")) {
                return objectPlayUrl.value("play_url").toString();
            }
        }
        if(document.isArray()) {
            qDebug() << "Array";
        }
    }
}

void MainWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(isPress) {
        // 窗口初始位置
        QPoint movePos = event->globalPos();
        move(movePos-movePoint);
    }
}

void MainWidget::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    isPress = false;
}

void MainWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton) {
        isPress = true;
        // 获取窗口当前位置与鼠标点击位置的偏移量
        movePoint = event->globalPos() - frameGeometry().topLeft();

/*
frameGeometry() 返回一个 QRect 对象，表示窗口的框架几何属性，包括窗口边框。它包含窗口的大小和位置。
topLeft() 是 QRect 类的一个成员函数，它返回一个 QPoint 对象，表示矩形区域的左上角的坐标。
*/
    }
}
